package com.dson.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Objects;

public class CookieUtil {

    public static String getCookie(HttpServletRequest request,String name){
        return Arrays.stream(request.getCookies())
                .filter(o -> Objects.equals(o.getName(),name))
                .findFirst()
                .map(Cookie::getValue)
                .orElse(null);
    }

    public static void setCookie(HttpServletResponse response, String name,String value,String domain){
        Cookie cookie = new Cookie(name, value);
        cookie.setDomain(domain);
        cookie.setPath("/");
        cookie.setMaxAge(Integer.MAX_VALUE);
        response.addCookie(cookie);
    }

    public static void clearCookie(HttpServletRequest request,HttpServletResponse response, String name){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if(Objects.equals(cookie.getName(),name)){
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                break;
            }
        }
    }
}
